package com.example.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class MyWebView extends WebView {
    private Context mContext;
    public MyWebView(Context context) {
        this(context, null);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setBackgroundColor(Color.TRANSPARENT);
        configWebview();
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        setBackgroundColor(Color.TRANSPARENT);
        configWebview();
    }
    private void configWebview() {

        setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String originalUrl) {
                if (mWebViewLoadListener != null && mWebViewLoadListener.shouldOverrideUrlLoading(view, originalUrl)) {
                    // 被自定义覆盖的方法处理了 就返回
                    return true;
                }
             return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (mWebViewLoadListener != null) {
                    mWebViewLoadListener.onPageStarted(view, url, favicon);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (mWebViewLoadListener != null) {
                    mWebViewLoadListener.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // TODO 自动生成的方法存根
                // super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (mWebViewLoadListener != null) {
                    mWebViewLoadListener.onReceivedError(view, request, error);
                }
            }
        });
        setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                if (mWebViewLoadListener != null) {
                    mWebViewLoadListener.onProgressChanged(view, progress);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                if (getContext() != null && !TextUtils.isEmpty(message)) {
                    Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
                }
                result.cancel();
                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String mtTitle) {
                super.onReceivedTitle(view, mtTitle);
                String title = mtTitle.replaceFirst("http://","").replaceFirst("https://","");
                String url = getUrl().replaceFirst("http://","").replaceFirst("https://","");
                if (!TextUtils.equals(title, url) && mWebViewLoadListener != null) {
                    mWebViewLoadListener.onReceivedTitle(view, mtTitle);
                }
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, android.webkit.GeolocationPermissions.Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser
                    (WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//                Toast.makeText(getContext(),"进入onShowFileChooser方法",Toast.LENGTH_LONG).show();

                return true;
            }
        });

        setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                getContext().startActivity(intent);
                if (getContext() instanceof Activity) {
                    ((Activity) getContext()).finish();
                }
            }
        });

        Log.i("UserAgent", getSettings().getUserAgentString());
        getSettings().setJavaScriptEnabled(true);//支持js
        getSettings().setBuiltInZoomControls(true);//设置支持缩放
        getSettings().setDisplayZoomControls(false);// 是否显示内置缩放控件
        getSettings().setUseWideViewPort(true);//将图片调整到适合webview的大小
        getSettings().setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        getSettings().setSavePassword(false);//关闭webview保存密码
        getSettings().setGeolocationEnabled(true);// 指定源的网页内容在没有设置权限状态下尝试使用地理位置API
        getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口

        getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //不能要缓存，不然网页头像会不及时更新
        getSettings().setDomStorageEnabled(true);// 启用HTML5 DOM 存储
        if (Build.VERSION.SDK_INT >= 21) {
            // 5.0以上允许加载http和https混合的页面(5.0以下默认允许，5.0+默认禁止)
            getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

//        移除有风险的接口漏洞
        removeJavascriptInterface("searchBoxJavaBridge_");
        removeJavascriptInterface("accessibility");
        removeJavascriptInterface("accessibilityTraversal");
    }

    boolean enable;

    public void setBoolean(boolean enable) {
        this.enable = enable;
    }
    @Override
    public void loadUrl(@NonNull String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        try {
            if("file".equals(Uri.parse(url).getScheme())){//判断是否为file协议
                if (enable) {
                    getSettings().setJavaScriptEnabled(true);
                }else {
                    getSettings().setJavaScriptEnabled(false);
                }
//            getSettings().setJavaScriptEnabled(false);
            }else{
                getSettings().setJavaScriptEnabled(true);
            }
            super.loadUrl(url);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static class WebViewLoadListener {
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        public void onPageFinished(WebView view, String url) {
        }

        public void onProgressChanged(WebView view, int progress) {
        }

        public void onReceivedTitle(WebView view, String mtTitle) {
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            if("file".equals(Uri.parse(url).getScheme())){//判断是否为file协议
//                view.getSettings().setJavaScriptEnabled(false);
//            }else{
//                view.getSettings().setJavaScriptEnabled(true);
//            }
            return false;
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        }

        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        }

        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        }
    }

    private WebViewLoadListener mWebViewLoadListener;

    public void setWebViewLoadListener(WebViewLoadListener mWebViewLoadListener) {
        this.mWebViewLoadListener = mWebViewLoadListener;
    }
}
